package com.matrix.tool.ui.tool

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.Environment
import android.view.View
import android.widget.SeekBar
import androidx.activity.enableEdgeToEdge
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.BusUtils.Bus
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.reflect.TypeToken
import com.jeremyliao.liveeventbus.LiveEventBus
import com.matrix.basecore.arouter.ARouterUtils
import com.matrix.basecore.base.BaseActivity
import com.matrix.basecore.constant.Constant
import com.matrix.tool.R
import com.matrix.tool.bean.CorpPath
import com.matrix.tool.databinding.ActivityGifBinding
import com.matrix.tool.utils.git_encoder.AnimatedGifEncoder
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import pl.droidsonroids.gif.GifDrawable
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.concurrent.thread

@Route(path = Constant.ARouterPath.GIFActivityPath)
class GIFActivity : BaseActivity<ActivityGifBinding>() {

    private lateinit var mGifDrawable: GifDrawable
    private var mPro = 1
    private var fps: Int = 1
    private var mWidth = 200
    private var mHeight = 200
    private lateinit var lastFilePath: String
    private var corp: ArrayList<String> = arrayListOf()

    override fun getViewBinding(): ActivityGifBinding {
        enableEdgeToEdge()
        return ActivityGifBinding.inflate(layoutInflater)
    }

    override fun initView() {
        EventBus.getDefault().register(this)
//        BusUtils.register(this)
        mViewBinding.includeTitle.tvTitle.text = "GIF制作"
        mViewBinding.seekbar.max = 14
        mViewBinding.seekbar.progress = mPro
    }

    override fun initData() {
        LiveEventBus
            .get(Constant.ARouterString.PATH, String::class.java)
            .observe(this) { param ->
                backCreateGIF(param)
            }
    }

    private fun backCreateGIF(param: String?) {
        mViewBinding.llEmpty.visibility = View.GONE
        val token: TypeToken<ArrayList<String?>?> =
            object : TypeToken<ArrayList<String?>?>() {}
        corp = GsonUtils.fromJson(param, token.type)
        val loadBitmap = BitmapFactory.decodeFile(corp[0])
        mWidth = loadBitmap.width
        mHeight = loadBitmap.height
        createGIF(fps, Constant.CachePath)
    }

//    @Bus(tag = "BusUtils")
//    fun oneParamFun(param: String?) {
//        LogUtils.i(param)
//    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getCorpEvent(corp: CorpPath) {
        backCreateGIF(corp.path)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
//        BusUtils.unregister(this)
    }

    override fun initListener() {
        mViewBinding.includeTitle.ivBack.setOnClickListener {
            finish()
        }

        mViewBinding.tvChoose.setOnClickListener {
            ARouterUtils.startGIFPhotoActivity()
        }
        mViewBinding.llEmpty.setOnClickListener {
            ARouterUtils.startGIFPhotoActivity()
        }

        mViewBinding.ivControl.setOnClickListener {
            if (::mGifDrawable.isInitialized) {
                if (mGifDrawable.isPlaying) {
                    mGifDrawable.pause()
                    mViewBinding.ivControl.setImageResource(R.mipmap.icon_play_end)
                } else {
                    mGifDrawable.start()
                    mViewBinding.ivControl.setImageResource(R.mipmap.icon_play_start)
                }
            }
        }
        mViewBinding.ivShare.setOnClickListener {
            if (::mGifDrawable.isInitialized) {
                val intent = Intent(Intent.ACTION_SEND)
                intent.type = "image/*" //设置MIME类型
                intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(lastFilePath)) //需要分享的文件URI
                startActivity(Intent.createChooser(intent, "分享"))
            }
        }

        mViewBinding.ivDownload.setOnClickListener {
            if (::mGifDrawable.isInitialized) {
                createGIF(mPro, Constant.GIFPath)
                ToastUtils.showShort("成功保存到文件 $lastFilePath")
            }
        }

        mViewBinding.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(p0: SeekBar?, progress: Int, fromUser: Boolean) {
                if (::mGifDrawable.isInitialized) {
                    if (fromUser) {
                        mPro = progress + 1
                        mGifDrawable.setSpeed(mPro.toFloat())
                    }
                }
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {

            }

            override fun onStopTrackingTouch(p0: SeekBar?) {

            }
        })
    }

    private fun createGIF(
        fps: Int,
        parentPath: String
    ) {
        thread {
            val baos = ByteArrayOutputStream()
            val localAnimatedGifEncoder: AnimatedGifEncoder = AnimatedGifEncoder()
            localAnimatedGifEncoder.start(baos) //start
            localAnimatedGifEncoder.setRepeat(0) //设置生成gif的开始播放时间。0为立即开始播放
            localAnimatedGifEncoder.setDelay(2000 / fps) //没帧的延迟时间 ms
            LogUtils.i(corp.toString())
            if (corp.size > 0) {
                for (item in corp) {
                    val bitmap = BitmapFactory.decodeFile(item)
                    val resizeBm: Bitmap = resizeImage(bitmap, mWidth, mHeight)
                    localAnimatedGifEncoder.addFrame(resizeBm)
                }
            }
            localAnimatedGifEncoder.finish() //finish
            val sdCardDir =
                File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path,
                    parentPath
                )
            var savePath = sdCardDir.path
            FileUtils.createOrExistsDir(savePath)

            if (!sdCardDir.exists()) {
                sdCardDir.mkdirs()
            }
            var filename = System.currentTimeMillis().toString() + ".gif"
            lastFilePath = savePath + File.separator + filename
            var fos: FileOutputStream? = null
            try {
                fos = FileOutputStream(lastFilePath)
                baos.writeTo(fos)
                baos.flush()
                fos.flush()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            try {
                baos.close()
                fos!!.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            runOnUiThread {
                try {
                    mGifDrawable = GifDrawable(lastFilePath)
                    mViewBinding.giv.setImageDrawable(mGifDrawable) //这里是实际决定资源的地方，优先级高于xml文件的资源定义
                    mGifDrawable.start()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun resizeImage(bitmap: Bitmap, w: Int, h: Int): Bitmap {
        val BitmapOrg = bitmap
        val width = BitmapOrg.width
        val height = BitmapOrg.height
        val newWidth = w
        val newHeight = h

        val scaleWidth = (newWidth.toFloat()) / width
        val scaleHeight = (newHeight.toFloat()) / height

        val matrix = Matrix()
        matrix.postScale(scaleWidth, scaleHeight)
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        return Bitmap.createBitmap(
            BitmapOrg, 0, 0, width,
            height, matrix, true
        )
    }
}